package com.ciwong.epaper.modules.me.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.event.EventBusFactory;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.me.adapter.OfflineBookAdapter;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.download.DownLoadDB;
import com.ciwong.epaper.util.download.DownLoadInfo;
import com.ciwong.epaper.util.download.DownloadStatus;
import com.ciwong.eventbus.EventBus;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.FileUtil;
import com.ciwong.mobilelib.utils.ThreadTask;
import com.ciwong.mobilelib.widget.IndicateText;

/**
 * 离线缓存 Created by res-jianpingliu on 2015/7/24.
 */
public class OfflineBookActivity extends BaseActivity
{
    private ListView offlineLv;

    private LinearLayout llEmpty;

    private IndicateText itCount;

    private View imgView;

    private List<DownLoadInfo> mOfflineFileList;

    private OfflineBookAdapter mAdapter;

    private List<EpaperInfo> mPapers;

    private  int mServiceId;

    /**
     * 设置activity的布局文件
     *
     * @return 布局文件的resId
     */
    @Override
    protected int setView()
    {
        return R.layout.activity_offline_directory;
    }

    /**
     * 获取界面元素
     */
    @Override
    protected void findViews()
    {
        offlineLv = (ListView) findViewById(R.id.offline_directory_lv);
        llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
        itCount = (IndicateText) findViewById(R.id.right_indicate_text);

    }

    @Override
    protected void initEvent()
    {
        offlineLv.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id)
            {
                String bookId = mPapers.get(position).getPackageId();
                ArrayList<DownLoadInfo> completedList = new ArrayList<DownLoadInfo>();
                for (DownLoadInfo info : mOfflineFileList)
                {
                    if (info.getBookId().equals(bookId))
                    {
                        completedList.add(info);
                    }
                }
                MeJumpManager.jumpToOfflineFiles(OfflineBookActivity.this,
                        completedList, mPapers.get(position).getProductName(),
                        R.string.go_back,mServiceId);
            }
        });
        setRightBtnListener(new ViewOnClickListener()
        {
            @Override
            public void avertRepeatOnClick(View v)
            {
                MeJumpManager.jumpToLoadingFiles(OfflineBookActivity.this,
                        R.string.go_back);
            }
        });
    }

    @Override
    protected void init()
    {
        setTitleText(R.string.offline_flies);
        EventBus.getDownLoadInstance().register(this);
        mPapers = new ArrayList<EpaperInfo>();
        mOfflineFileList = new ArrayList<DownLoadInfo>();

        mAdapter = new OfflineBookAdapter(this, mPapers);
        offlineLv.setAdapter(mAdapter);

        mServiceId = getIntent().getIntExtra(IntentFlag.INTENT_FLAG_SERVICE_ID, -1);
    }

    @Override
    protected void loadData()
    {

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        ThreadTask.getInstance().executorDBThread(new Runnable()
        {
            @Override
            public void run()
            {
                final int count = DownLoadDB.queryUnCompletedList().size();
                mOfflineFileList = DownLoadDB.queryCompletedList();
                final List<EpaperInfo> tempList = getOffLineList();
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        if (count == 0)
                        {
                            hideRightBtn();
                            itCount.setVisibility(View.GONE);
                        }
                        else
                        {
                            setRightBtnBG(R.drawable.selector_icon_downing);
                            itCount.setVisibility(View.VISIBLE);
                            itCount.setText(count + "");
                        }

                        mPapers.clear();
                        mPapers.addAll(tempList);
                        mAdapter.notifyDataSetChanged();
                    }
                });
            }
        }, ThreadTask.ThreadPeriod.PERIOD_HIGHT);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        EventBus.getDownLoadInstance().unregister(this);
    }

    public void showLlEmpty()
    {
        if (llEmpty != null)
        {
            llEmpty.setVisibility(View.VISIBLE);
        }
    }

    public void hideLlEmpty()
    {
        if (llEmpty != null)
        {
            llEmpty.setVisibility(View.GONE);
        }
    }

    public void onEventMainThread(EventBusFactory.DownloadEvent item)
    {
        DownLoadInfo info = item.getInfo();
        if (info != null && info.getStatus() == DownloadStatus.STATUS_COMPLETED)
        {
            onResume();
        }
    }

    private List<EpaperInfo> getOffLineList()
    {
        List<EpaperInfo> list = new ArrayList<EpaperInfo>();
        for (DownLoadInfo info : mOfflineFileList)
        {
            try
            {
                String packageDir = ESystem.getPackagesCatalogue(
                        info.getBookId(), info.getChapterId());
                if (!new File(packageDir).exists())
                {
                    continue;
                }
                EpaperInfo epaperInfo = new EpaperInfo();
                epaperInfo.setPackageId(info.getBookId() + "");
                epaperInfo.setProductName(info.getBookName());
                epaperInfo.setCover(info.getIconUrl());
                epaperInfo.setIsFree(info.getIsFree());
                epaperInfo.setRequired(info.getIsKaoShi());
                File file = new File(packageDir);
                long length = FileUtil.getFolderSize(file);
                if (list.contains(epaperInfo))
                {
                    EpaperInfo tempInfo = list.get(list.indexOf(epaperInfo));
                    tempInfo.setLength(tempInfo.getLength() + length);
                    tempInfo.setSize(tempInfo.getSize() + 1);
                }
                else
                {
                    epaperInfo.setLength(length);
                    epaperInfo.setSize(1);
                    list.add(epaperInfo);
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return list;
    }

}
